package gnss

type IgmasSsrCorrectionHead struct {
	MsgId    uint16
	Tow      uint32 // Glo是天内 时间, 其系统是周内 时间
	UpIntv   uint8
	SyncFlag uint8 // Multiple Message Indicator
	Refd     uint8 // Satellite Reference Datum

	IOD    uint8
	ProvID uint16
	SolID  uint8
}

func DecodeIgmasSsrHead(head *IgmasSsrCorrectionHead, inBuf []byte, startBitN int) (bitN int, satn int) {
	bitN = startBitN
	head.MsgId = GetBitU16(inBuf, bitN, 12)
	bitN += 12

	head.Tow = GetBitU32(inBuf, bitN, 20)
	bitN += 20

	head.UpIntv = GetBitU8(inBuf, bitN, 4)
	bitN += 4

	head.SyncFlag = GetBitU8(inBuf, bitN, 1)
	bitN += 1

	if head.MsgId == 1057 || head.MsgId == 1063 || head.MsgId == 1060 {
		head.Refd = GetBitU8(inBuf, bitN, 1)
		bitN += 1
	}

	head.IOD = GetBitU8(inBuf, bitN, 4)
	bitN += 4

	head.ProvID = GetBitU16(inBuf, bitN, 16)
	bitN += 16

	head.SolID = GetBitU8(inBuf, bitN, 4)
	bitN += 4

	satn = int(GetBitU8(inBuf, bitN, 6))
	bitN += 6
	return
}

func EncodeIgmasSsrHead(head *IgmasSsrCorrectionHead, outBuf []byte, startBitN int, satn int) (bitN int) {
	bitN = startBitN
	SetBitU16(outBuf, bitN, 12, head.MsgId)
	bitN += 12

	if head.MsgId >= 1063 && head.MsgId <= 1068 {
		// DF386
		SetBitU32(outBuf, bitN, 17, head.Tow)
		bitN += 17
	} else {
		SetBitU32(outBuf, bitN, 20, head.Tow)
		bitN += 20
	}

	SetBitU8(outBuf, bitN, 4, head.UpIntv)
	bitN += 4

	SetBitU8(outBuf, bitN, 1, head.SyncFlag)
	bitN += 1

	// 轨道改正
	if head.MsgId == 1057 || head.MsgId == 1063 || head.MsgId == 1060 {
		SetBitU8(outBuf, bitN, 1, head.Refd)
		bitN += 1
	}

	SetBitU8(outBuf, bitN, 4, head.IOD)
	bitN += 4

	SetBitU16(outBuf, bitN, 16, head.ProvID)
	bitN += 16

	SetBitU8(outBuf, bitN, 4, head.SolID)
	bitN += 4

	SetBitU8(outBuf, bitN, 6, byte(satn))
	bitN += 6

	return
}
